package com.theatre.userservice.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.theatre.userservice.mapper.MenuMapper;
import com.theatre.userservice.mapper.UserMapper;
import com.theatre.userservice.model.entity.Menu;
import com.theatre.userservice.model.entity.User;
import com.theatre.userservice.model.vo.MenuVO;
import com.theatre.userservice.service.MenuService;
import com.theatre.userservice.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public List<MenuVO> selectMenusByRoleId(Long roleId) {
        List<Menu> menus = menuMapper.selectMenusByRoleId(roleId);
        List<Menu> treeMenus = buildMenuTree(menus);
        return convertToVOList(treeMenus);
    }

    private List<Menu> buildMenuTree(List<Menu> menus) {
        Map<Long, List<Menu>> childrenMap = new HashMap<>();
        for (Menu m : menus) {
            Long pid = toLong(m.getParentId());
            childrenMap.computeIfAbsent(pid, k -> new ArrayList<>()).add(m);
        }
        for (Menu m : menus) {
            m.setChildren(childrenMap.getOrDefault(m.getId(), new ArrayList<>()));
        }
        List<Menu> roots = new ArrayList<>();
        if (childrenMap.containsKey(null)) roots.addAll(childrenMap.get(null));
        if (childrenMap.containsKey(0L)) roots.addAll(childrenMap.get(0L));
        return roots;
    }

    private List<MenuVO> convertToVOList(List<Menu> menus) {
        if (menus == null) return new ArrayList<>();
        return menus.stream().map(menu -> {
            MenuVO vo = new MenuVO();
            vo.setId(menu.getId());
            vo.setMenuName(menu.getMenuName());
            vo.setMenuUrl(menu.getMenuUrl());
            vo.setChildren(convertToVOList(menu.getChildren()));
            return vo;
        }).collect(Collectors.toList());
    }

    private Long toLong(Object obj) {
        if (obj == null) return null;
        if (obj instanceof Long) return (Long) obj;
        if (obj instanceof Integer) return ((Integer) obj).longValue();
        if (obj instanceof String) {
            try { return Long.parseLong((String)obj); } catch (NumberFormatException e) { return null; }
        }
        return null;
    }
}
